package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PeachblossomVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description：test
 * @Create by： 张会豪
 * @Date：2021/11/7 9:56
 */
@Service
public class PeachblossomService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //桃花传音-发送语音
    public UserInfo peachblossom(MultipartFile soundFile) throws IOException, ParseException {
        //1、接收文件，将语音文件存入Oss中，返回文件url地址
        String url = ossTemplate.upload(soundFile.getOriginalFilename(),
                soundFile.getInputStream());
        //2、组装movement部分属性
        Long userId = UserHolder.getUserId();
        Movement movement = new Movement();
        movement.setUserId(userId);
        List<String> urls = new ArrayList<>();
        urls.add(url);
        movement.setMedias(urls);
        //增加yyyy-MM-dd时间点
        movement.setCreated2(new SimpleDateFormat("yyyy-MM-dd").parse(DateUtil.today()));

        //3、调用movementApi将动态发布，保存在movement表中
        //4、保存进redis，计数
        String key = Constants.PEACHBLOSSOM_USER_KEY + userId.toString();
        Long a = 8L;
        String hashKey1 = Constants.PEACHBLOSSOM_HASH_KEY + a.toString();
        if ("8".equals(redisTemplate.opsForHash().get(key, hashKey1))) {
            throw new BusinessException(ErrorResult.countError());
        }
        Long count = movementApi.sendVoice(movement);
        String hashKey = Constants.PEACHBLOSSOM_HASH_KEY + count.toString();
        redisTemplate.opsForHash().put(key, hashKey, count.toString());

        //5、组建userInfo对象
        UserInfo userInfo = userInfoApi.findById(userId);
        //设置剩余次数
        String result = redisTemplate.opsForHash().get(key, hashKey).toString();
        Integer integer = Integer.valueOf(result);
        int flag = 8 - integer;
        if (flag < 0) {
            throw new BusinessException(ErrorResult.countError());
        }
        return userInfo;
    }

    @Autowired
    private TanhuaService tanhuaService;

    //桃花传音-接收语言
    public PeachblossomVo acceptPeachblossom() throws ParseException {
        //1、随机在movement表中查询一个语音消息
        List<Movement> movementList = movementApi.acceptOne(1);
        //1.1、获取该集合中
        String key = Constants.PEACHBLOSSOM_USER_DELETE_KEY + UserHolder.getUserId().toString();
        Long a = 8L;
        String hashKey1 = Constants.PEACHBLOSSOM_HASH_KEY + a.toString();
        if ("8".equals(redisTemplate.opsForHash().get(key, hashKey1))) {
            throw new BusinessException(ErrorResult.countError());
        }
        if (CollUtil.isEmpty(movementList)) {
            throw new BusinessException(ErrorResult.error());
        }
        Movement movement = movementList.get(0);
        //2、听完语音后，如果选择喜欢
        //3、听完语音后，如果选择不喜欢
        //3.6、调用movementApi删除该条语音动态
        List<String> medias = movement.getMedias();
        movementApi.delete(movement.getId());
        if(CollUtil.isNotEmpty(medias)){
            for (String url : medias) {
                //3.7、调用OssTemplate删除该条语音url
                ossTemplate.deleteFile(url);
            }
        }
        //存入当前用户
        Movement movement1 = new Movement();
        movement1.setUserId(UserHolder.getUserId());
        movement1.setCreated3(new SimpleDateFormat("yyyy-MM-dd").parse(DateUtil.today()));
        movementApi.publish(movement1);
        //设置redis
        Long aLong = movementApi.sendVoice(movement1);
        String hashKey = Constants.PEACHBLOSSOM_HASH_KEY + aLong.toString();
        redisTemplate.opsForHash().put(key, hashKey, aLong.toString());


        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        PeachblossomVo vo = PeachblossomVo.init(userInfo, movement);

        //设置剩余次数
        String result = redisTemplate.opsForHash().get(key, hashKey).toString();
        Integer integer = Integer.valueOf(result);
        int flag = 8 - integer;
        if (flag < 0) {
            throw new BusinessException(ErrorResult.countError());
        } else {
            vo.setRemainingTimes(flag);
        }
        return vo;
    }
}
